#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "childwnd.h"
#include <QMdiSubWindow>
#include <QCloseEvent>
#include <QFileDialog>
#include <QFontDialog>
#include <QColorDialog>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    initMainWindow();

    connect(ui->saveAction, SIGNAL(triggered(bool)), this, SLOT(on_saveAction_triggered()));

    connect(ui->saveAsAction, SIGNAL(triggered(bool)), this, SLOT(on_saveAsAction_triggered()));
    connect(ui->undoAction, SIGNAL(triggered(bool)), this, SLOT(on_undoAction_triggered()));
    connect(ui->redoAction, SIGNAL(triggered(bool)), this, SLOT(on_redoAction_triggered()));
    connect(ui->cutAction, SIGNAL(triggered(bool)), this, SLOT(on_cutAction_triggered()));
    connect(ui->copyAction, SIGNAL(triggered(bool)), this, SLOT(on_copyAction_triggered()));
    connect(ui->boldAction, SIGNAL(triggered(bool)), this, SLOT(on_boldAction_triggered()));
    connect(ui->italicAction, SIGNAL(triggered(bool)), this, SLOT(on_italicAction_triggered()));
    connect(ui->underlineAction, SIGNAL(triggered(bool)), this, SLOT(on_underlineAction_triggered()));
    connect(ui->colorAction, SIGNAL(triggered(bool)), this, SLOT(on_fontColorChanged()));
    connect(ui->leftAlignAction, SIGNAL(triggered(bool)), this, SLOT(on_leftAlignAction_triggered()));
    connect(ui->centerAction, SIGNAL(triggered(bool)), this, SLOT(on_centerAction_triggered()));
    connect(ui->rightAlignAction, SIGNAL(triggered(bool)), this, SLOT(on_rightAlignAction_triggered()));
    connect(ui->justifyAction, SIGNAL(triggered(bool)), this, SLOT(on_justifyAction_triggered()));
}


MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initMainWindow()
{
    //初始化字号列表项
    QFontDatabase fontdb;
    foreach(int fontsize,fontdb.standardSizes())
        ui->sizeComboBox->addItem(QString::number(fontsize));

    QFont defFont;
    QString sFontSize;
    int defFontSize;
    int defFontindex;

    defFont = QApplication::font();
    defFontSize = defFont.pointSize();
    sFontSize = QString::number(defFontSize);
    defFontindex =ui->sizeComboBox->findText(sFontSize);

    ui->sizeComboBox->setCurrentIndex(defFontindex);

    ui->mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    ui->mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

    refreshMenus();
    connect(ui->mdiArea,&QMdiArea::subWindowActivated,
    this,&MainWindow::refreshMenus);

    addSubWndListMenu();
    connect(ui->menu_W,&QMenu::aboutToShow,
    this,&MainWindow::addSubWndListMenu);

    m_WndMapper = new QSignalMapper(this);
    connect(m_WndMapper,SIGNAL(mapped(QWidget*)),
            this,SLOT(setActiveSubWindow(QWidget*)));

}

void MainWindow::docNew()
{
    ChildWnd *childwnd = new ChildWnd;
    ui->mdiArea->addSubWindow(childwnd);
    connect(childwnd,SIGNAL(copyAvailable(bool)),
    ui->cutAction,SLOT(setEnabled(bool)));
    connect(childwnd,SIGNAL(copyAvailable(bool)),
    ui->copyAction,SLOT(setEnabled(bool)));

    childwnd->newDoc();
    childwnd->show();
    formatEnabled();
}

void MainWindow::docOpen()
{
    QString docName = QFileDialog::getOpenFileName(this,
                                   "打开文档",
                                    "",
                                   "文本文件(*.txt);;"
                                   "HTML文件(*.html *.htm;;"
                                   "所有文件(*.*)");
    if(!docName.isEmpty()){
    QMdiSubWindow *existWnd = findChildWnd(docName);
    if(existWnd)
    {
    ui->mdiArea->setActiveSubWindow(existWnd);
    return;
    }
    ChildWnd *childWnd= new ChildWnd;
    ui->mdiArea->addSubWindow(childWnd);

    connect(childWnd,SIGNAL(copyAvailable(bool)),
    ui->cutAction,SLOT(setEnabled(bool)));
    connect(childWnd,SIGNAL(copyAvailable(bool)),
    ui->copyAction,SLOT(setEnabled(bool)));

    if(childWnd->loadDoc(docName)){
    statusBar()->showMessage("文档已打开",3000);
    childWnd->show();
    formatEnabled();
    }else{

    childWnd->close();
    }
    }
}

void MainWindow::formatEnabled()
{
    ui->boldAction->setEnabled(true);
    ui->italicAction->setEnabled(true);
    ui->underlineAction->setEnabled(true);
    ui->leftAlignAction->setEnabled(true);
    ui->centerAction->setEnabled(true);
    ui->rightAlignAction->setEnabled(true);
    ui->justifyAction->setEnabled(true);
    ui->colorAction->setEnabled(true);

}

ChildWnd *MainWindow::activatechildWnd()
{
    QMdiSubWindow* actWnd = ui->mdiArea->activeSubWindow();
    //actWnd是SubWindow类型，我们需要把他转换为ChildWnd类型
    if(actWnd)
        return qobject_cast<ChildWnd*>(actWnd->widget());
    else
        return nullptr;
}

QMdiSubWindow *MainWindow::findChildWnd(const QString &docName)
{
    QString strFile =QFileInfo(docName).canonicalFilePath();
    foreach (QMdiSubWindow* subWnd,ui->mdiArea->subWindowList())
    {
        ChildWnd* chilWnd = qobject_cast<ChildWnd*>(subWnd->widget());
        if(chilWnd->m_CurDocPath == strFile) return subWnd;
    }
    return 0;
}

void MainWindow::on_newAction_triggered()
{
    docNew();
}

void MainWindow::refreshMenus()
{
    bool hasChild;
    hasChild = (activatechildWnd() !=0);

    ui->saveAction->setEnabled(hasChild);
    ui->saveAsAction->setEnabled(hasChild);
    ui->printAction->setEnabled(hasChild);
    ui->printPreviewAction->setEnabled(hasChild);
    ui->closeAction->setEnabled(hasChild);
    ui->closeAllAction->setEnabled(hasChild);
    ui->titleAction->setEnabled(hasChild);
    ui->cascadeAction->setEnabled(hasChild);
    ui->nextAction->setEnabled(hasChild);
    ui->previousAction->setEnabled(hasChild);

    bool hasSelect = (activatechildWnd() &&
                      activatechildWnd()->textCursor().hasSelection());

    ui->cutAction->setEnabled(hasSelect);
    ui->copyAction->setEnabled(hasSelect);
    ui->boldAction->setEnabled(hasSelect);
    ui->italicAction->setEnabled(hasSelect);
    ui->underlineAction->setEnabled(hasSelect);
    ui->leftAlignAction->setEnabled(hasSelect);
    ui->centerAction->setEnabled(hasSelect);
    ui->rightAlignAction->setEnabled(hasSelect);
    ui->justifyAction->setEnabled(hasSelect);
    ui->colorAction->setEnabled(hasSelect);
}

void MainWindow::addSubWndListMenu()
{
    ui->menu_W->clear();
    ui->menu_W->addAction(ui->closeAction);
    ui->menu_W->addAction(ui->closeAllAction);
    ui->menu_W->addSeparator();
    ui->menu_W->addAction(ui->titleAction);
    ui->menu_W->addAction(ui->cascadeAction);
    ui->menu_W->addSeparator();
    ui->menu_W->addAction(ui->nextAction);
    ui->menu_W->addAction(ui->previousAction);
    QList<QMdiSubWindow*> wnds = ui->mdiArea->subWindowList();

    if(!wnds.isEmpty()) ui->menu_W->addSeparator();

    for(int i = 0;i< wnds.size(); ++i)
    {
        ChildWnd* childWnd = qobject_cast<ChildWnd*>(wnds.at(i)->widget());
        QString menuitem_text;
        menuitem_text=QString("%1 %2")
        .arg(i+1)
        .arg(childWnd->getcurDocName());

        QAction *menuitem_act = ui->menu_W->addAction(menuitem_text);
        menuitem_act->setCheckable(true);
        menuitem_act->setChecked(childWnd == activatechildWnd());

        connect(menuitem_act,SIGNAL(triggered(bool)),
                m_WndMapper,SLOT(map()));

        m_WndMapper->setMapping(menuitem_act,wnds.at(i));


    }

    formatEnabled();

}

void MainWindow::on_closeAction_triggered()
{
    ui->mdiArea->closeActiveSubWindow();
}

void MainWindow::on_closeAllAction_triggered()
{
    ui->mdiArea->closeAllSubWindows();
}

void MainWindow::on_titleAction_triggered()
{
    ui->mdiArea->tileSubWindows();
}

void MainWindow::on_cascadeAction_triggered()
{
    ui->mdiArea->cascadeSubWindows();
}

void MainWindow::on_nextAction_triggered()
{
    ui->mdiArea->activateNextSubWindow();
}

void MainWindow::on_previousAction_triggered()
{
    ui->mdiArea->activatePreviousSubWindow();
}

void MainWindow::setActiveSubWindow(QWidget *wnd)
{
    if(!wnd) return;
        ui->mdiArea->setActiveSubWindow(qobject_cast<QMdiSubWindow*>(wnd));
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    ui->mdiArea->closeAllSubWindows();
    if(ui->mdiArea->currentSubWindow())
    //忽略此事件
    event->ignore();
    else
    event->accept();
    //接受此事件
}

void MainWindow::on_openAction_triggered()
{
    docOpen();
}

void MainWindow::on_saveAction_triggered()
{
    ChildWnd* childWnd = activatechildWnd();//获取当前活动窗口
    if(childWnd)
    {
        childWnd->saveDoc();
    }
}

void MainWindow::on_saveAsAction_triggered()
{
    ChildWnd* childWnd = activatechildWnd();//获取当前活动窗口
    if(childWnd)
    {
        childWnd->saveAsDoc();
    }
}

void MainWindow::on_undoAction_triggered()
{
    ChildWnd *childWnd = activatechildWnd();
    if (childWnd) {
        childWnd->undo();
    }
}

void MainWindow::on_redoAction_triggered()
{
    ChildWnd *childWnd = activatechildWnd();
    if (childWnd) {
        childWnd->redo();
    }
}

void MainWindow::on_cutAction_triggered()
{
    ChildWnd *childWnd = activatechildWnd();
    if (childWnd) {
        childWnd->cut();
    }
}

void MainWindow::on_copyAction_triggered()
{
    ChildWnd *childWnd = activatechildWnd();
    if (childWnd) {
        childWnd->copy();
    }
}


void MainWindow::on_boldAction_triggered()
{
    ChildWnd *childWnd = activatechildWnd();
    if (childWnd) {
        QTextCharFormat fmt;
        fmt.setFontWeight(ui->boldAction->isChecked() ? QFont::Bold : QFont::Normal);
        childWnd->mergeCurrentCharFormat(fmt);
    }
}

void MainWindow::on_italicAction_triggered()
{
    ChildWnd *childWnd = activatechildWnd();
    if (childWnd) {
        QTextCharFormat fmt;
        fmt.setFontItalic(ui->italicAction->isChecked());
        childWnd->mergeCurrentCharFormat(fmt);
    }
}

void MainWindow::on_underlineAction_triggered()
{
    ChildWnd *childWnd = activatechildWnd();
    if (childWnd) {
        QTextCharFormat fmt;
        fmt.setFontUnderline(ui->underlineAction->isChecked());
        childWnd->mergeCurrentCharFormat(fmt);
    }
}



void MainWindow::on_fontColorChanged()
{
    ChildWnd *childWnd = activatechildWnd();
    if (childWnd) {
        QColor color = QColorDialog::getColor(Qt::black, this);
        if (color.isValid()) {
            QTextCharFormat fmt;
            fmt.setForeground(color);
            childWnd->mergeCurrentCharFormat(fmt);
        }
    }
}


void MainWindow::on_leftAlignAction_triggered() {
    ChildWnd *childWnd = activatechildWnd();
    if (childWnd) {
        QTextCursor cursor = childWnd->textCursor();
        QTextBlockFormat blockFormat;
        blockFormat.setAlignment(Qt::AlignLeft); // 设置左对齐
        cursor.mergeBlockFormat(blockFormat);
        childWnd->setTextCursor(cursor);
    }
}

void MainWindow::on_centerAction_triggered() {
    ChildWnd *childWnd = activatechildWnd();
    if (childWnd) {
        QTextCursor cursor = childWnd->textCursor();
        QTextBlockFormat blockFormat;
        blockFormat.setAlignment(Qt::AlignCenter); // 设置居中对齐
        cursor.mergeBlockFormat(blockFormat);
        childWnd->setTextCursor(cursor);
    }
}

void MainWindow::on_rightAlignAction_triggered() {
    ChildWnd *childWnd = activatechildWnd();
    if (childWnd) {
        QTextCursor cursor = childWnd->textCursor();
        QTextBlockFormat blockFormat;
        blockFormat.setAlignment(Qt::AlignRight); // 设置右对齐
        cursor.mergeBlockFormat(blockFormat);
        childWnd->setTextCursor(cursor);
    }
}

void MainWindow::on_justifyAction_triggered() {
    ChildWnd *childWnd = activatechildWnd();
    if (childWnd) {
        QTextCursor cursor = childWnd->textCursor();
        QTextBlockFormat blockFormat;
        blockFormat.setAlignment(Qt::AlignJustify); // 设置两端对齐
        cursor.mergeBlockFormat(blockFormat);
        childWnd->setTextCursor(cursor);
    }
}
